<?php

class UserController extends BaseController {

    private $tempDir = 'Temp';

    public function index() {

        $Options  = Cache::get('options');
        $aClasses = [];

        foreach (Classes::all() as $key => $oClass) {
            $aClasses[$oClass->course][$oClass->id] = $oClass;
        }

        $aData = array(
            'classes'           => $aClasses,
            'sPage_Title'       => trans('navigation.manage-user.list'),
            'sPage_Description' => trans('navigation.manage-user-description.list'),
            'aCourse'           => $Options['COURSE'],
            'aTeams'            => $Options['NGANH'],
            'aLevels'           => $Options['CAP'],
            'aCrews'            => $Options['DOI'],
            'aRole'             => Role::where('type', 'GROUP')->get(),
        );
        return View::make("user.page", $aData);
    }

    public function postAjaxUserList() {
        $aResponse = [];

        if (Request::get('sAction') && Request::get('sGroupActionName')) {

            $aResponse['sStatus'] = 'OK';

            switch (Request::get('sGroupActionName')) {
                case 'delete':
                    User::whereIn('id', Request::get('id'))->delete();
                    $aResponse['sMessage'] = trans('user-pages.list.message.delete', array('IDs' => implode(', ', Request::get('id'))));
                    break;

                case 'setclass':
                    $oClass = Classes::find(Request::get('class_id'));
                    $aUsers = User::whereIn('id', Request::get('id'))->get();

                    if ($oClass && $aUsers) {

                        $aClass_ID  = Classes::where('course', '=', $oClass->course)->lists('id');
                        $aUserError = $aUserAdded = [];

                        foreach ($aUsers as $oUser) {

                            if (!empty($aClass_ID)) {

                                $oOldClass = $oUser->classes()->whereIn('class_id', $aClass_ID);

                                if (in_array(Request::get('class_id'), $oOldClass->lists('class_id'))) {
                                    // Has been added
                                    $aUserError[$oUser->id] = "$oUser->id: " . $oClass->generateClassName();
                                } else if ($oOldClass->first() && $oUser->isThieuNhi()) {
                                    // Only 1 class/student/course
                                    $aUserError[$oUser->id] = "$oUser->id: " . $oOldClass->first()->generateClassName();
                                } else {
                                    $oUser->classes()->attach(Request::get('class_id'), [
                                        'updater' => Auth::user()->id,
                                        'rank'    => $oUser->isThieuNhi() ? 'KHUYEN_KHICH' : '',
                                    ]);

                                    $aUserAdded[$oUser->id] = "$oUser->id: " . $oClass->generateClassName();
                                }
                            }
                        }

                        $aResponse['sMessage'] = trans('validation.custom.success-title') . '<ul><li>' . implode("</li><li>", $aUserAdded + $aUserError) . '</li></ul>';
                    }
                    break;

                case 'assign_permission':
                    $oRole      = Role::find(Request::get('role_id'));
                    $aUsers     = User::whereIn('id', Request::get('id'))->get();
                    $aUserError = $aUserAdded = [];

                    if ($oRole && $aUsers) {

                        foreach ($aUsers as $oUser) {

                            try {
                                $oUser->roles()->attach([Request::get('role_id')], [
                                    'updater' => Auth::user()->id
                                ]);

                                $aUserAdded[$oUser->id] = "$oUser->id: " . trans('permission.role.name') . ' "' . $oRole->name . '"';
                            } catch (Exception $exc) {
                                $aUserError[$oUser->id] = "$oUser->id: " . trans('permission.role.name') . ' "' . $oRole->name . '"';
                            }
                        }

                        $aResponse['sMessage'] = trans('validation.custom.success-title') . '<ul><li>' . implode("</li><li>", $aUserAdded + $aUserError) . '</li></ul>';
                    }
                    break;

                case 'export_excel':

                    $aUsers = User::whereIn('id', Request::get('id'));

                    /*
                     * Ordering
                     */
                    $aColumns = array('checkbox', 'id', 'username', 'birthday', 'phone', 'actions');
                    if (Request::get('iSortCol_0')) {
                        for ($i = 0; $i < Request::get('iSortingCols'); $i++) {
                            if (Request::get('bSortable_' . Request::get('iSortCol_' . $i)) == "true") {
                                if ($aColumns[Request::get('iSortCol_' . $i)] == 'username') {
                                    $aUsers->orderBy('firstname', Request::get('sSortDir_' . $i) === 'asc' ? 'asc' : 'desc');
                                } else {
                                    $aUsers->orderBy($aColumns[Request::get('iSortCol_' . $i)], Request::get('sSortDir_' . $i) === 'asc' ? 'asc' : 'desc');
                                }
                            }
                        }
                    }

                    $aUsers = $aUsers->get();

                    if ($aUsers) {
                        $aRow = [
                            [
                                trans('user.userid'),
                                trans('user.saint'),
                                trans('user.username'),
                                trans('user.firstname'),
                                trans('user.gender-name'),
                                trans('user.birthday'),
                                trans('user.phone'),
                                trans('user.address'),
                                trans('user.baptism-date'),
                                trans('user.eucharist-date'),
                                trans('user.confirmation-date'),
                                trans('user.usertype'),
                                trans('user.usercrew'),
                                trans('user.email'),
                                trans('user.parish'),
                                trans('user.gencode'),
                                trans('dear.dear-title'),
                            ]
                        ];

                        foreach ($aUsers as $user) {
                            $dears = $user->dears()->get();

                            if ($dears) {
                                $aTmp = [];
                                foreach ($dears as $dear) {
                                    $aTmp[] = "$dear->saint $dear->dearname $dear->phone";
                                }
                            }

                            $aRow[] = [
                                'user.userid'            => $user->id,
                                'user.saint'             => $user->saint,
                                'user.username'          => $user->username,
                                'user.firstname'         => $user->firstname,
                                'user.gender-name'       => trans('user.gender.' . $user->gender),
                                'user.birthday'          => CNamHoa::ConvertDate($user->birthday),
                                'user.phone'             => $user->phone,
                                'user.address'           => $user->address,
                                'user.baptism-date'      => CNamHoa::ConvertDate($user->baptism_date),
                                'user.eucharist-date'    => CNamHoa::ConvertDate($user->eucharist_date),
                                'user.confirmation-date' => CNamHoa::ConvertDate($user->confirmation_date),
                                'user.usertype'          => $user->usertype,
                                'user.usercrew'          => $user->usercrew,
                                'user.email'             => $user->email,
                                'user.parish'            => $user->parish,
                                'user.gencode'           => $user->gencode,
                                'dear.dear-title'        => $dears ? implode(" | ", $aTmp) : null,
                            ];
                        }

                        $file = Excel::create(strtotime('now') . '_export', function($excel) use($aRow) {

                                $excel->sheet('Export', function($sheet) use($aRow) {

                                    $sheet->fromArray($aRow);
                                });
                            })
                            ->store('xls', $this->tempDir, true);

                        $aResponse['sMessage'] = trans('validation.custom.success-title') . ' ' . trans('user-pages.list.message.export-excel', ['filePath' => Config::get('app.url') . '/' . $file['full']]);
                    } else {
                        $aResponse['sStatus'] = '';
                    }
                    break;

                default:
                    $aResponse['sMessage'] = trans('user-pages.list.message.delete', array('IDs' => implode(', ', Request::get('id'))));
                    break;
            }
        }

        // <editor-fold defaultstate="collapsed" desc="Filter Data">
        /* Individual column filtering */
        $aUsers  = DB::table('user');
        $Classes = new Classes;
        $bFlag   = false;

        $aColumns = array('course', 'team', 'level', 'crew');
        foreach ($aColumns as $sColumnName) {
            if (Request::get('filter_' . $sColumnName)) {
                $Classes = $Classes->where($sColumnName, Request::get('filter_' . $sColumnName));
                $bFlag   = true;
            }
        }

        if ($bFlag) {

            $Classes = $Classes->lists('id');

            if (empty($Classes)) {
                return $this->generateResponse();
            }

            $aUserID = DB::table('user_class')->whereIn('class_id', $Classes)->lists('user_id');

            if (empty($aUserID)) {
                return $this->generateResponse();
            }

            $aUsers->whereIn('id', $aUserID);
        }

        $aColumns = array('id', 'saint', 'username', 'birthdayfrom', 'birthdayto', 'phone');
        foreach ($aColumns as $sColumnName) {
            if (Request::get('filter_' . $sColumnName)) {

                switch ($sColumnName) {
                    case 'birthdayfrom':
                        $sTempDate = CNamHoa::ConvertDate(Request::get('filter_' . $sColumnName));
                        $aUsers->where('birthday', '>=', $sTempDate);
                        break;
                    case 'birthdayto':
                        $sTempDate = CNamHoa::ConvertDate(Request::get('filter_' . $sColumnName));
                        $aUsers->where('birthday', '<=', $sTempDate);
                        break;
                    default:
                        $aUsers->where($sColumnName, 'like', '%' . Request::get('filter_' . $sColumnName) . '%');
                        break;
                }
            }
        }

        /*
         * Ordering
         */
        $aColumns = array('checkbox', 'id', 'username', 'birthday', 'phone', 'actions');
        if (Request::get('iSortCol_0')) {
            for ($i = 0; $i < Request::get('iSortingCols'); $i++) {
                if (Request::get('bSortable_' . Request::get('iSortCol_' . $i)) == "true") {
                    if ($aColumns[Request::get('iSortCol_' . $i)] == 'username') {
                        $aUsers->orderBy('firstname', Request::get('sSortDir_' . $i) === 'asc' ? 'asc' : 'desc');
                    } else {
                        $aUsers->orderBy($aColumns[Request::get('iSortCol_' . $i)], Request::get('sSortDir_' . $i) === 'asc' ? 'asc' : 'desc');
                    }
                }
            }
        }

        $iTotalRecords = $aUsers->count();

        /*
         * Paging
         */
        if (Request::get('iDisplayLength') != '-1') {
            $aUsers->skip(Request::get('iDisplayStart'))->take(Request::get('iDisplayLength'));
        }
        // </editor-fold>

        $aUsers = $aUsers->get();

        foreach ($aUsers as $key => $user) {
            $aUsers[$key]->checkbox = '<input type="checkbox" name="id[]" value="' . $user->id . '">';
            $aUsers[$key]->username = $aUsers[$key]->saint . ' - ' . $aUsers[$key]->username;
            $aUsers[$key]->username = trim($aUsers[$key]->username, ' - ');
            $aUsers[$key]->birthday = CNamHoa::ConvertDate($user->birthday);
            $aUsers[$key]->actions  = '<a href="' . route('profile', ['id' => $user->id]) . '" class="btn btn-xs default btn-edit"><i class="fa fa-search"></i> ' . trans('system.button.view') . '</a>';
        }

        return $this->generateResponse($aResponse, $iTotalRecords, $aUsers);
    }

    private function generateResponse($aResponse = [], $iTotalRecords = 0, $aUsers = []) {

        $aResponse = $aResponse + array(
            "iTotalRecords"        => User::count(),
            "iTotalDisplayRecords" => $iTotalRecords,
            "sEcho"                => Request::get('sEcho'),
            'aaData'               => $aUsers
        );

        return Response::json($aResponse);
    }

    public function getCreation() {

        $Options = Cache::get('options');
        $iCourse = CNamHoa::CurrentCourse();
        $aData   = array(
            'sPage_Title'       => trans('navigation.manage-user.create'),
            'sPage_Description' => trans('navigation.manage-user-description.create'),
            'Options'           => $Options,
            'iCourse'           => $iCourse,
            'Classes'           => Classes::where('course', $iCourse)->get(),
        );

        return View::make("user.new", $aData);
    }

    public function postCreation() {
        $sFirstName = explode(" ", trim(Input::get('username')));
        $sFirstName = end($sFirstName);
        $sNewID     = CNamHoa::generateUserID(Input::get('usertype'));
        $User       = new User;

        $User->id                = $sNewID;
        $User->saint             = Input::get('saint');
        $User->username          = Input::get('username');
        $User->passwd            = Hash::make(Input::get('password'));
        $User->gender            = Input::get('gender');
        $User->phone             = Input::get('phone');
        $User->address           = Input::get('address');
        $User->birthday          = CNamHoa::ConvertDate(Input::get('birthday'));
        $User->baptism_date      = CNamHoa::ConvertDate(Input::get('baptism_date'));
        $User->eucharist_date    = CNamHoa::ConvertDate(Input::get('eucharist_date'));
        $User->confirmation_date = CNamHoa::ConvertDate(Input::get('confirmation_date'));
        $User->usertype          = Input::get('usertype');
        $User->usercrew          = Input::get('usercrew');
        $User->firstname         = $sFirstName;
        $User->email             = Input::get('email');
        $User->parish            = Input::get('parish');
        $User->updater           = Auth::user()->id;
        $User->save();

        $User = $User->find($sNewID);

        if (Input::get('class_id')) {
            $User->classes()->attach(Input::get('class_id'));
        }

        if (Input::get('dearname')) {
            $Dear = new UserDear([
                'relationship' => Input::get('relationship'),
                'saint'        => Input::get('dearsaint'),
                'dearname'     => Input::get('dearname'),
                'address'      => Input::get('dearaddress'),
                'phone'        => Input::get('dearphone'),
                'updater'      => Auth::user()->id,
            ]);

            $User->dears()->save($Dear);
        }

        return Redirect::route('home');
    }

    public function postAjaxCreationByFile() {
        $file      = Input::file('file');
        $aResponse = [
            "code" => 200
        ];

        $newFileName   = strtotime('now') . "_import." . $file->getClientOriginalExtension();
        $uploadSuccess = $file->move($this->tempDir, $newFileName);

        if (!is_object($uploadSuccess)) {

            $aResponse["code"] = 0;
        } else {

            try {
                $userData = Excel::load($this->tempDir . "/$newFileName", true)->calculate()->toArray();
                $userData = array_shift($userData); // First Sheet
                $iCourse  = CNamHoa::CurrentCourse();

                foreach ($userData as $ID => $Info) {

                    foreach ($Info as $key => $value) {
                        $Info[$key] = trim($value);
                    }

                    $Info['dien_thoai'] = trim($Info['dien_thoai'] . ' | ' . $Info['mobile'], ' | ');
                    $Info['ngay_sinh']  = str_replace('/', '-', $Info['ngay_sinh']);
                    $Info['ngay_sinh']  = CNamHoa::ConvertDate($Info['ngay_sinh']);
                    $Info['gioi_tinh']  = $Info['gioi_tinh'] == 'NAM' ? 1 : 0;

                    if ($Info['nganh']) {
                        $Classes = Classes::firstOrCreate([
                                'course' => $iCourse,
                                'team'   => $Info['nganh'],
                                'level'  => $Info['cap'],
                                'crew'   => $Info['doi'],
                        ]);

                        $Info['class_id'] = $Classes->id;
                    } else {
                        $Info['class_id'] = '';
                    }

                    $TempUser = [
                        "id"                => '',
                        "saint"             => $Info['ten_thanh'],
                        "username"          => $Info['ho_ten'],
                        "usertype"          => Input::get('usertype'),
                        "gender"            => $Info['gioi_tinh'],
                        "phone"             => $Info['dien_thoai'],
                        "address"           => $Info['dia_chi'],
                        "birthday"          => $Info['ngay_sinh'],
                        "baptism_date"      => $Info['ngay_rua_toi'],
                        "eucharist_date"    => $Info['ngay_ruoc_le'],
                        "confirmation_date" => $Info['ngay_them_suc'],
                        "parish"            => $Info['giao_ho'],
                        'class_id'          => $Info['class_id'],
                        'father_saint'      => $Info['ten_thanh_cha'],
                        'father_name'       => $Info['ho_ten_cha'],
                        'mother_saint'      => $Info['ten_thanh_me'],
                        'mother_name'       => $Info['ho_ten_me'],
                    ];


                    $userData[$ID] = $TempUser;
                }

                $cacheID = strtotime('now');

                Cache::put($cacheID, $userData, 120);
                $aResponse ["cacheID"] = $cacheID;
            } catch (Exception $exc) {
                $aResponse["code"] = 0;
            }
        }

        File::delete($this->tempDir . "/$newFileName");

        return Response::json($aResponse);
    }

    public function postAjaxCreationByFileTable($cacheID) {

        if (!Cache::has($cacheID)) {
            $aResponse = [
                "iTotalRecords"        => 0,
                "iTotalDisplayRecords" => 0,
                "sEcho"                => Request::get('sEcho'),
                'aaData'               => []
            ];

            return Response::json($aResponse);
        }

        $userData = Cache::get($cacheID);

        if (Input::get('sAction') == 'group_action' && Input::get('sGroupActionName')) {

            $IDs = Input::get('id');
            switch (Input::get('sGroupActionName')) {
                case 'delete':
                    foreach ($IDs as $ID) {
                        unset($userData[$ID]);
                    }
                    break;

                case 'new':
                    // <editor-fold defaultstate="collapsed" desc="Create User">
                    foreach ($IDs as $ID) {

                        if (isset($userData[$ID])) {

                            try {
                                $Info       = $userData[$ID];
                                $sNewID     = CNamHoa::generateUserID($Info['usertype']);
                                $sFirstName = explode(" ", trim($Info['username']));
                                $sFirstName = end($sFirstName);

                                User::create([
                                    "id"                => $sNewID,
                                    "saint"             => $Info['saint'],
                                    "username"          => $Info['username'],
                                    "firstname"         => $sFirstName,
                                    "usertype"          => $Info['usertype'],
                                    "passwd"            => Hash::make($sNewID),
                                    "gender"            => $Info['gender'],
                                    "phone"             => $Info['phone'],
                                    "address"           => $Info['address'],
                                    "birthday"          => $Info['birthday'],
                                    "baptism_date"      => $Info['baptism_date'],
                                    "eucharist_date"    => $Info['eucharist_date'],
                                    "confirmation_date" => $Info['confirmation_date'],
                                    "parish"            => $Info['parish'],
                                    "updater"           => Auth::user()->id,
                                ]);

                                $User = User::find($sNewID);

                                $userData[$ID]['id'] = $sNewID; // Update Cache

                                if ($Info['class_id']) {
                                    $User->classes()->attach($Info['class_id']);
                                }

                                if ($Info['father_name']) {
                                    $Dear = new UserDear([
                                        'relationship' => 'CHA',
                                        'saint'        => $Info['father_saint'],
                                        'dearname'     => $Info['father_name'],
                                        'updater'      => Auth::user()->id,
                                    ]);

                                    $User->dears()->save($Dear);
                                }

                                if ($Info['mother_name']) {
                                    $Dear = new UserDear([
                                        'relationship' => 'ME',
                                        'saint'        => $Info['mother_saint'],
                                        'dearname'     => $Info['mother_name'],
                                        'updater'      => Auth::user()->id,
                                    ]);

                                    $User->dears()->save($Dear);
                                }
                            } catch (Exception $exc) {
                                
                            }
                        }
                    }
                    // </editor-fold>
                    break;

                default:
                    break;
            }
            Cache::put($cacheID, $userData, 120);
        }

        $aaData = [];

        foreach ($userData as $ID => $Info) {

            // Inserted or Not
            if ($Info['id']) {
                $sCheckboxButt = $Info['id'];
                $sActionsButt  = '<a target="_blank" href="' . route('profile', ['id' => $sCheckboxButt]) . '" class="btn btn-xs default btn-edit"><i class="fa fa-search"></i> ' . trans('system.button.view') . '</a>';
            } else {
                $sCheckboxButt = '<input type="checkbox" name="id[]" value="' . $ID . '">';
                $sActionsButt  = '<button data-href="' . route('create-user-by-file-edit', [$cacheID, $ID]) . '" class="btn default yellow-stripe btn-xs btn-edit"><i class="fa fa-pencil"></i> ' . trans('system.button.edit') . '</button>';
            }

            $aaData[$ID] = array_merge($Info, [
                "checkbox" => $sCheckboxButt,
                "birthday" => CNamHoa::ConvertDate($Info['birthday']),
                "gender"   => trans('user.gender.' . $Info['gender']),
                "class"    => $Info['class_id'] ? Classes::find($Info['class_id'])->generateClassName(true) : null,
                "actions"  => $sActionsButt,
            ]);
        }

        $aaData = array_slice($aaData, Request::get('iDisplayStart'), Request::get('iDisplayLength'));

        $aResponse = array(
            "iTotalRecords"        => count($userData),
            "iTotalDisplayRecords" => count($userData),
            "sEcho"                => Request::get('sEcho'),
            'aaData'               => $aaData
        );

        return Response::json($aResponse);
    }

    public function getAjaxCreationByFileEdit($cacheID, $ID) {
        $User   = new stdClass();
        $Option = Cache::get('options');

        if (Cache::has($cacheID)) {
            $userData = Cache::get($cacheID);

            if (isset($userData[$ID]))
                $User = (object) $userData[$ID];
        }

        return View::make("user.new-modal", [
                'User'    => $User,
                'Classes' => Classes::where('course', CNamHoa::CurrentCourse())->get(),
                'Option'  => $Option,
                'route'   => route('create-user-by-file-edit', [$cacheID, $ID]),
        ]);
    }

    public function postAjaxCreationByFileEdit($cacheID, $ID) {
        $Option = Cache::get('options');

        if (Cache::has($cacheID)) {
            $userData = Cache::get($cacheID);

            $userData[$ID]["id"]                = Input::get("id");
            $userData[$ID]["saint"]             = Input::get("saint");
            $userData[$ID]["username"]          = Input::get("username");
            $userData[$ID]["gender"]            = Input::get("gender");
            $userData[$ID]["phone"]             = Input::get("phone");
            $userData[$ID]["address"]           = Input::get("address");
            $userData[$ID]["birthday"]          = CNamHoa::ConvertDate(Input::get("birthday"));
            $userData[$ID]["baptism_date"]      = CNamHoa::ConvertDate(Input::get("baptism_date"));
            $userData[$ID]["eucharist_date"]    = CNamHoa::ConvertDate(Input::get("eucharist_date"));
            $userData[$ID]["confirmation_date"] = CNamHoa::ConvertDate(Input::get("confirmation_date"));
            $userData[$ID]["parish"]            = Input::get("parish");
            $userData[$ID]['class_id']          = Input::get('class_id');
            $userData[$ID]['father_saint']      = Input::get('father_saint');
            $userData[$ID]['father_name']       = Input::get('father_name');
            $userData[$ID]['mother_saint']      = Input::get('mother_saint');
            $userData[$ID]['mother_name']       = Input::get('mother_name');

            Cache::put($cacheID, $userData, 120);

            $aResponse = ["code" => 200];
        } else {
            $aResponse = ["code" => 0];
        }

        return Response::json($aResponse);
    }

}
